// 好友请求状态管理
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { friendRequestService } from '@/services'
import type { 
  FriendRequest, 
  SendFriendRequestRequest,
  FriendRequestStatus 
} from '@/types'

export const useFriendRequestsStore = defineStore('friendRequests', () => {
  // 状态
  const receivedRequests = ref<FriendRequest[]>([])
  const sentRequests = ref<FriendRequest[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  // 计算属性
  const pendingReceivedRequests = computed(() => 
    receivedRequests.value.filter(req => req.status === 'PENDING')
  )
  
  const pendingSentRequests = computed(() => 
    sentRequests.value.filter(req => req.status === 'PENDING')
  )
  
  const pendingRequestCount = computed(() => pendingReceivedRequests.value.length)
  
  const hasUnreadRequests = computed(() => pendingRequestCount.value > 0)
  
  // 操作方法
  
  /**
   * 发送好友请求
   */
  async function sendFriendRequest(request: SendFriendRequestRequest): Promise<FriendRequest> {
    try {
      isLoading.value = true
      error.value = null
      
      const friendRequest = await friendRequestService.sendFriendRequest(request)
      
      // 添加到发送列表
      sentRequests.value.unshift(friendRequest)
      
      return friendRequest
    } catch (err) {
      error.value = err instanceof Error ? err.message : '发送好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 接受好友请求
   */
  async function acceptFriendRequest(requestId: number, userId: number): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendRequestService.acceptFriendRequest(requestId, userId)
      
      // 更新本地状态
      const request = receivedRequests.value.find(req => req.id === requestId)
      if (request) {
        request.status = 'ACCEPTED'
        request.processedAt = new Date()
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '接受好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 拒绝好友请求
   */
  async function rejectFriendRequest(requestId: number, userId: number, reason?: string): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendRequestService.rejectFriendRequest(requestId, userId, reason)
      
      // 更新本地状态
      const request = receivedRequests.value.find(req => req.id === requestId)
      if (request) {
        request.status = 'REJECTED'
        request.rejectReason = reason
        request.processedAt = new Date()
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '拒绝好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 取消好友请求
   */
  async function cancelFriendRequest(requestId: number, userId: number): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendRequestService.cancelFriendRequest(requestId, userId)
      
      // 更新本地状态
      const request = sentRequests.value.find(req => req.id === requestId)
      if (request) {
        request.status = 'CANCELLED'
        request.processedAt = new Date()
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '取消好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 加载收到的好友请求
   */
  async function loadReceivedRequests(userId: number, refresh = false): Promise<void> {
    try {
      if (refresh || receivedRequests.value.length === 0) {
        isLoading.value = true
        error.value = null
      }
      
      const requests = await friendRequestService.getAllReceivedRequests(userId)
      receivedRequests.value = requests
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载收到的好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 加载发送的好友请求
   */
  async function loadSentRequests(userId: number, refresh = false): Promise<void> {
    try {
      if (refresh || sentRequests.value.length === 0) {
        isLoading.value = true
        error.value = null
      }
      
      const requests = await friendRequestService.getAllSentRequests(userId)
      sentRequests.value = requests
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载发送的好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 加载所有好友请求
   */
  async function loadAllRequests(userId: number, refresh = false): Promise<void> {
    await Promise.all([
      loadReceivedRequests(userId, refresh),
      loadSentRequests(userId, refresh)
    ])
  }
  
  /**
   * 批量处理好友请求
   */
  async function batchProcessRequests(
    requests: { requestId: number; action: 'accept' | 'reject'; reason?: string }[],
    userId: number
  ): Promise<{ success: number; failed: number; errors: string[] }> {
    try {
      isLoading.value = true
      error.value = null
      
      const result = await friendRequestService.batchProcessRequests(requests, userId)
      
      // 更新本地状态
      requests.forEach(req => {
        const request = receivedRequests.value.find(r => r.id === req.requestId)
        if (request) {
          request.status = req.action === 'accept' ? 'ACCEPTED' : 'REJECTED'
          if (req.reason) request.rejectReason = req.reason
          request.processedAt = new Date()
        }
      })
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '批量处理好友请求失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 检查是否可以发送好友请求
   */
  async function canSendFriendRequest(fromUserId: number, toUserId: number): Promise<boolean> {
    try {
      return await friendRequestService.canSendFriendRequest(fromUserId, toUserId)
    } catch (err) {
      console.error('检查发送权限失败:', err)
      return false
    }
  }
  
  /**
   * 处理实时通知
   */
  function handleFriendRequestNotification(notification: any): void {
    switch (notification.type) {
      case 'FRIEND_REQUEST_RECEIVED':
        // 添加新的好友请求到收到列表
        if (notification.data.requestId) {
          const newRequest: FriendRequest = {
            id: notification.data.requestId,
            fromUserId: notification.fromUserId,
            toUserId: notification.toUserId,
            message: notification.data.message,
            status: 'PENDING',
            createdAt: new Date(notification.timestamp),
            updatedAt: new Date(notification.timestamp),
            expiredAt: notification.data.expiredAt ? new Date(notification.data.expiredAt) : undefined
          }
          receivedRequests.value.unshift(newRequest)
        }
        break
        
      case 'FRIEND_REQUEST_ACCEPTED':
        // 更新发送列表中的请求状态
        if (notification.data.requestId) {
          const request = sentRequests.value.find(req => req.id === notification.data.requestId)
          if (request) {
            request.status = 'ACCEPTED'
            request.processedAt = new Date(notification.data.processedAt)
          }
        }
        break
        
      case 'FRIEND_REQUEST_REJECTED':
        // 更新发送列表中的请求状态
        if (notification.data.requestId) {
          const request = sentRequests.value.find(req => req.id === notification.data.requestId)
          if (request) {
            request.status = 'REJECTED'
            request.rejectReason = notification.data.rejectReason
            request.processedAt = new Date(notification.data.processedAt)
          }
        }
        break
        
      case 'FRIEND_REQUEST_CANCELLED':
        // 从收到列表中移除取消的请求
        if (notification.data.requestId) {
          const index = receivedRequests.value.findIndex(req => req.id === notification.data.requestId)
          if (index !== -1) {
            receivedRequests.value[index].status = 'CANCELLED'
            receivedRequests.value[index].processedAt = new Date(notification.data.processedAt)
          }
        }
        break
    }
  }
  
  /**
   * 根据状态过滤请求
   */
  function getRequestsByStatus(type: 'received' | 'sent', status: FriendRequestStatus): FriendRequest[] {
    const requests = type === 'received' ? receivedRequests.value : sentRequests.value
    return requests.filter(req => req.status === status)
  }
  
  /**
   * 获取请求统计信息
   */
  const requestStats = computed(() => ({
    received: {
      total: receivedRequests.value.length,
      pending: pendingReceivedRequests.value.length,
      accepted: getRequestsByStatus('received', 'ACCEPTED').length,
      rejected: getRequestsByStatus('received', 'REJECTED').length
    },
    sent: {
      total: sentRequests.value.length,
      pending: pendingSentRequests.value.length,
      accepted: getRequestsByStatus('sent', 'ACCEPTED').length,
      rejected: getRequestsByStatus('sent', 'REJECTED').length,
      cancelled: getRequestsByStatus('sent', 'CANCELLED').length
    }
  }))
  
  /**
   * 清除错误状态
   */
  function clearError(): void {
    error.value = null
  }
  
  /**
   * 重置状态
   */
  function reset(): void {
    receivedRequests.value = []
    sentRequests.value = []
    isLoading.value = false
    error.value = null
  }
  
  return {
    // 状态
    receivedRequests,
    sentRequests,
    isLoading,
    error,
    
    // 计算属性
    pendingReceivedRequests,
    pendingSentRequests,
    pendingRequestCount,
    hasUnreadRequests,
    requestStats,
    
    // 方法
    sendFriendRequest,
    acceptFriendRequest,
    rejectFriendRequest,
    cancelFriendRequest,
    loadReceivedRequests,
    loadSentRequests,
    loadAllRequests,
    batchProcessRequests,
    canSendFriendRequest,
    handleFriendRequestNotification,
    getRequestsByStatus,
    clearError,
    reset
  }
})